#include "widget.h"
#include "ui_widget.h"
#include <QtWidgets/QMessageBox>
#include <QtSql>
#include <QTime>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->lineEdit_Port->setText("1234");
    ui->pushButton_Send->setEnabled(false);


    m_server = new QTcpServer();
    //sx
    socket_list = new QList<QTcpSocket*>;

    connect(m_server,&QTcpServer::newConnection,this,&Widget::server_New_Connect);

}

Widget::~Widget()
{
    m_server->close();
    m_server->deleteLater();
    delete ui;
}

 void Widget::server_New_Connect()
 {
     //获取客户端连接
    m_socket = m_server->nextPendingConnection();   //获取已经建立的连接的Tcp套接字，使用它来完成数据的发送和其它操作
    //sx
    socket_list->append(m_socket);

    QObject::connect(m_socket,&QTcpSocket::readyRead,this,&Widget::socket_Recv_Data);
    QObject::connect(m_socket,&QTcpSocket::disconnected,this,&Widget::socket_Disconnect);

    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append(tr("Client连接！%1\n").arg(QTime::currentTime().toString()));
    ui->pushButton_Send->setEnabled(true);

 }

void Widget:: socket_Recv_Data()    //接收来自多个客户端的信息并分割展示
{

    //sx
    for(int i = 0;i < socket_list->length();i ++){  //加上for循环可以实现多个客户端
        QByteArray data_tmp;
        data_tmp = socket_list->at(i)->readAll();
        if(!data_tmp.isEmpty())
        {
            QString str = QString(data_tmp);

            //提取发送方的名字、发送内容
            QStringList info = str.split("#");

            QString name = info[0];
            QString message = info[1];

            //展示，设置文字颜色、灰度、字体、格式
            ui->textBrowser->setTextColor(Qt::gray);
            ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
            ui->textBrowser->append("From Client: " + name + " Time: " + QTime::currentTime().toString());

             ui->textBrowser->setTextColor(Qt::black);
             ui->textBrowser->setCurrentFont(QFont("Times New Roman",16));
            ui->textBrowser->append(message);

            QTextCursor cursor = ui->textBrowser->textCursor(); //自动下拉至底部
            cursor.movePosition(QTextCursor::End);
            ui->textBrowser->setTextCursor(cursor);
        }
    }

}

void Widget:: socket_Disconnect()   //客户端断开连接后显示信息
{
    ui->pushButton_Send->setEnabled(false);
    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append(tr("Client离开！%1\n").arg(QTime::currentTime().toString()));

}

void Widget::on_pushButton_Listen_clicked() //监听按钮的操作，负责启动、断开服务器对端口监听
{
    if (ui->pushButton_Listen->text() ==QString("监听"))
        {
        qint16 port = ui->lineEdit_Port->text().toInt();

        if(!m_server->listen(QHostAddress::Any, port))
        {
            QMessageBox::critical(this,"Error！",m_server->errorString(),QMessageBox::Yes | QMessageBox::No,QMessageBox::Yes );
            return;

        }
        ui->pushButton_Listen->setText("取消监听");

    }
    else
    {
        if(m_socket->state() == QAbstractSocket::ConnectedState)
        {
            m_socket->disconnectFromHost();
        }
        m_server->close();

        ui->pushButton_Listen->setText("监听");
        ui->pushButton_Send->setEnabled(false);
    }
}

void Widget::on_pushButton_Send_clicked()   //发送按钮按下的操作，即向多个用户广发
{
    if (ui->textEdit->toPlainText() == QString())
    {
        QMessageBox msgb;
        msgb.setText("不能发送空消息！");
        msgb.resize(60,40);
        msgb.exec();
        return;
    }

    for(int i = 0;i < socket_list->length();i ++){  //加上for循环可以实现多个客户端
        socket_list->at(i)->write(ui->textEdit->toPlainText().toUtf8());
    }

    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append("From Server:  "+QTime::currentTime().toString());

     ui->textBrowser->setTextColor(Qt::black);
     ui->textBrowser->setCurrentFont(QFont("Times New Roman",16));
    ui->textBrowser->append(ui->textEdit->toPlainText().toUtf8());
    m_socket->flush();
    ui->textEdit->clear();


}

void Widget::on_pushButton_testMysql_clicked()  //测试从数据库中读取信息显示在控制台
{
    QSqlDatabase qDatabases = QSqlDatabase::addDatabase("QMYSQL");
        //设置相关参数
        qDatabases.setDatabaseName("flow");    // 需要与数据库中的一致
        qDatabases.setHostName("127.0.0.1");    // 主机名(地址)
        qDatabases.setPort(3306);        // 端口
        qDatabases.setUserName("root");  //设置用户名
        qDatabases.setPassword("");  //设置密码
        // 打开数据库
        if (qDatabases.open( )) {
            qDebug() << "open database";

            //数据库查询操作
            QSqlQuery query;
            query.exec("select name from test");
            QSqlRecord rec = query.record();
            while(query.next())
            {
                rec = query.record();
                int no = rec.indexOf("name");
                QString value = query.value(no).toString();
                qDebug()<<"name:"<<value;
            }
            //关闭数据库
            qDatabases.close();
        }else{
            QMessageBox::warning(NULL,"警告","无法连接数据库");
        }

}
